import {HTTP} from '../util/http-p.js'
class KeyWordModel extends HTTP{
  key = 'q'
  maxLength = 10
  // 获取历史搜索关键词
  getHistory() { 
    const words = wx.getStorageSync(this.key)
    if(!words) {
      return []
    }
    return words
  }

  // 获取热门的关键词
  getHot() {
    return this.request({
      url: '/book/hot_keyword'
    })
  }

  // 关键词写入缓存
  addToHistory(keyword) {
    let words = this.getHistory()
    const has = words.includes(keyword)
    // 该函数实现了一个队列---栈
    if(!has) {
      // 如果数组长度超出定义的长度，则删除尾部元素，把关键词添加到数组首位
      const length = words.length
      if(length >= this.maxLength) {
        words.pop()
      }
      words.unshift(keyword)
      wx.setStorageSync(this.key, words)
    }
  }
}

export {
  KeyWordModel
}